import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../core/constants/app_constants.dart';
import '../../shared/storage/storage_service.dart';
import '../../core/viewmodels/auth_viewmodel.dart';
import '../../core/services/call_manager_service.dart';

class SplashPage extends StatefulWidget {
  const SplashPage({super.key});

  @override
  State<SplashPage> createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _fadeAnimation;
  late Animation<double> _scaleAnimation;

  @override
  void initState() {
    super.initState();
    _setupAnimations();
    _navigateToHome();
  }

  void _setupAnimations() {
    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 1500),
    );

    _fadeAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(
      CurvedAnimation(
        parent: _animationController,
        curve: const Interval(0.0, 0.6, curve: Curves.easeIn),
      ),
    );

    _scaleAnimation = Tween<double>(
      begin: 0.5,
      end: 1.0,
    ).animate(
      CurvedAnimation(
        parent: _animationController,
        curve: const Interval(0.0, 0.8, curve: Curves.easeOut),
      ),
    );

    _animationController.forward();
  }

  void _navigateToHome() async {
    // 延迟显示动画，然后根据登录状态跳转
    await Future.delayed(
      Duration(seconds: AppConstants.splashDelaySeconds),
    );
    
    if (!mounted) return;
    
    // 检查是否已登录（延迟检查，确保 token 已保存）
    final storageService = StorageService();
    final token = await storageService.getToken();
    
    if (token != null && token.isNotEmpty) {
      // 已登录，恢复用户信息到 ViewModel
      try {
        final authViewModel = context.read<AuthViewModel>();
        await authViewModel.checkLoginStatus();
        // 等待一下，确保用户信息已恢复
        await Future.delayed(const Duration(milliseconds: 100));
        
        // 刷新全局通话管理服务的好友列表和用户ID
        try {
          final callManagerService = CallManagerService();
          await callManagerService.refreshFriends();
        } catch (e) {
          debugPrint('刷新 CallManagerService 失败: $e');
        }
      } catch (e) {
        // 恢复失败，继续跳转（用户信息可能为空，但不会影响跳转）
        debugPrint('恢复用户信息失败: $e');
      }
      
      if (!mounted) return;
      
      // 已登录，跳转到首页
      Navigator.of(context).pushReplacementNamed(
        AppConstants.routeHome,
      );
    } else {
      // 未登录，跳转到登录页
      Navigator.of(context).pushReplacementNamed(
        AppConstants.routeLogin,
      );
    }
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: [
              Theme.of(context).colorScheme.primary,
              Theme.of(context).colorScheme.secondary,
            ],
          ),
        ),
        child: Center(
          child: AnimatedBuilder(
            animation: _animationController,
            builder: (context, child) {
              return FadeTransition(
                opacity: _fadeAnimation,
                child: ScaleTransition(
                  scale: _scaleAnimation,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(
                        Icons.chat_bubble_outline,
                        size: 100,
                        color: Colors.white,
                      ),
                      const SizedBox(height: 24),
                      Text(
                        'Violet',
                        style: TextStyle(
                          fontSize: 32,
                          fontWeight: FontWeight.bold,
                          color: Colors.white,
                          letterSpacing: 2,
                        ),
                      ),
                    ],
                  ),
                ),
              );
            },
          ),
        ),
      ),
    );
  }
}

